<?php
/**
 * @purpose 分销
 * User: peter
 * Date: 2018/9/5
 * Time: 下午8:19
 */

namespace app\mall\logic;


use app\model\MemberIncome;
use app\model\UpgradeAgentOrder;
use think\facade\Log;

class Distribution
{
    /**
     * @purpose 代理商升级分佣
     * @param string $order_no
     * @param int $uid
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function agentUpgrade (string $order_no, int $uid): bool
    {
        Log::write('开始分销:', 'notice');
        $order          = new UpgradeAgentOrder();
        $member         = new \app\model\Member();
        $distribution   = new \app\model\Distribution();
        $income         = new MemberIncome();
        $member->startTrans();
        // 获取代理商升级时的分销比例
        $distribution_ratio     = Configure::getConfigure('distribution_ratio');
        $distribution_ratio     = $distribution_ratio['data'];
        if (!$distribution_ratio['switch']) {
            Log::write('分销系统已经关闭!', 'notice');
            return false;
        }
        $order_info     = $order
            ->alias('o')
            ->lock(true)
            ->join('member m', 'o.uid=m.uid')
            ->where([
                'o.order_no' => $order_no,
                'o.uid' => $uid
            ])
            ->field('o.id,o.uid,o.order_no,o.pay_money,o.is_distribution,m.invitation_from,m.nickname')
            ->find();
        if (!$order_info) {
            Log::write('代理商升级分销订单未找到!', 'notice');
            return false;
        }
        if ($order_info->is_distribution === 2) {
            Log::write('该笔代理商升级订单已分销!', 'notice');
            return true;
        }
        if ($order_info->invitation_from === 'self') {
            Log::write('当前代理商没有上级!', 'notice');
            return true;
        }
        // 获取父级用户信息
        $parent                 = $member
            ->where('invitation', $order_info->invitation_from)
            ->field('uid,invitation,agent,invitation_from')
            ->find();
        Log::write('parent_info: '.json_encode($parent->toArray()), 'notice');
        // 如果父级为会员
        $distribution_parent_member_result  = true;
        $distribution_parent_member_bonus_result  = true;
        $distribution_parent_member_income  = true;
        if ($parent->agent === 1) {
            // 获取父级会员的分佣比例
            $ratio  = ((int) $distribution_ratio['purchase_agent_member']['first'] / 100);
            // 记录分佣数据
            $quota = (int) ($order_info->pay_money *  $ratio);
            $distribution_parent_member_result  = $distribution
                ->isUpdate(false)
                ->data([
                    'uid'           => $parent->uid,
                    'from_uid'      => $order_info->uid,
                    'status'        => 2,
                    'type'          => 2,
                    'quota'         => $quota,
                    'level'         => 1,
                    'order_id'      => $order_info->id,
                    'transfer_at'   => time()
                ])
                ->save();
            // 给父级会员分佣
            $distribution_parent_member_bonus_result = $member
                ->where('uid', $parent->uid)
                ->setInc('balance', $quota);
            // 记录父级会员收入记录
            $distribution_parent_member_income = $income
                ->isUpdate(false)
                ->data([
                    'uid' => $parent->uid,
                    'type' => 2,
                    'quota' => $quota,
                    'description' => '一级盟友['.$order_info->nickname.']',
                    'from_uid' => $order_info->uid
                ])
                ->save();
        }
        // 如果父级为代理商
        $distribution_parent_agent_result = true;
        $distribution_parent_agent_bonus_result = true;
        $distribution_parent_agent_bonus_income = true;
        if ($parent->agent === 2) {
            // 获取父级代理商的分佣比例
            $ratio  = ((int) $distribution_ratio['purchase_agent_agent']['first'] / 100);
            // 记录分佣数据
            $quota = (int) ($order_info->pay_money *  $ratio);
            $distribution_parent_agent_result  = $distribution
                ->isUpdate(false)
                ->data([
                    'uid'           => $parent->uid,
                    'from_uid'      => $order_info->uid,
                    'status'        => 2,
                    'type'          => 2,
                    'quota'         => $quota,
                    'level'         => 1,
                    'order_id'      => $order_info->id,
                    'transfer_at'   => time()
                ])
                ->save();
            // 给父级代理商分佣
            $distribution_parent_agent_bonus_result = $member
                ->where('uid', $parent->uid)
                ->setInc('balance', $quota);
            // 记录父级代理商收入记录
            $distribution_parent_agent_bonus_income = $income
                ->isUpdate(false)
                ->data([
                    'uid' => $parent->uid,
                    'type' => 2,
                    'quota' => $quota,
                    'description' => '一级盟友['.$order_info->nickname.']',
                    'from_uid' => $order_info->uid
                ])
                ->save();
        }
        if ($parent->invitation_from === 'self') {
            if (
                $distribution_parent_member_result &&
                $distribution_parent_member_bonus_result &&
                $distribution_parent_agent_result &&
                $distribution_parent_agent_bonus_result &&
                $distribution_parent_member_income &&
                $distribution_parent_agent_bonus_income
            ) {
                $member->commit();
                return true;
            }
            return false;
        }
        $grand_pa       = $member
            ->where('invitation', $parent->invitation_from)
            ->field('uid,invitation,agent,invitation_from')
            ->find();
        // 如果父级的父级为会员
        $distribution_grand_pa_member_result  = true;
        $distribution_grand_pa_member_bonus_result  = true;
        $distribution_grand_pa_member_bonus_income  = true;
        if ($grand_pa->agent === 1) {
            // 获取父级的父级会员的分佣比例
            $ratio  = ((int) $distribution_ratio['purchase_agent_member']['second'] / 100);
            // 记录分佣数据
            $quota = (int) ($order_info->pay_money *  $ratio);
            $distribution_grand_pa_member_result  = $distribution
                ->data([
                    'uid'           => $grand_pa->uid,
                    'from_uid'      => $order_info->uid,
                    'status'        => 2,
                    'type'          => 2,
                    'quota'         => $quota,
                    'level'         => 1,
                    'order_id'      => $order_info->id,
                    'transfer_at'   => time()
                ])
                ->save();
            // 给父级的父级会员分佣
            $distribution_grand_pa_member_bonus_result = $member
                ->where('uid', $grand_pa->uid)
                ->setInc('balance', $quota);
            // 记录父级的父级代理商收入记录
            $distribution_grand_pa_member_bonus_income = $income
                ->isUpdate(false)
                ->data([
                    'uid' => $grand_pa->uid,
                    'type' => 2,
                    'quota' => $quota,
                    'description' => '二级盟友['.$order_info->nickname.']',
                    'from_uid' => $order_info->uid
                ])
                ->save();
        }
        // 如果父级的父级为代理商
        $distribution_grand_pa_agent_result = true;
        $distribution_grand_pa_agent_bonus_result = true;
        $distribution_grand_pa_agent_bonus_income = true;
        if ($grand_pa->agent === 2) {
            // 获取父级的父级代理商的分佣比例
            $ratio  = ((int) $distribution_ratio['purchase_agent_agent']['second'] / 100);
            // 记录分佣数据
            $quota = (int) ($order_info->pay_money *  $ratio);
            $distribution_grand_pa_agent_result  = $distribution
                ->data([
                    'uid'           => $grand_pa->uid,
                    'from_uid'      => $order_info->uid,
                    'status'        => 2,
                    'type'          => 2,
                    'quota'         => $quota,
                    'level'         => 1,
                    'order_id'      => $order_info->id,
                    'transfer_at'   => time()
                ])
                ->save();
            // 给父级的父级会员分佣
            $distribution_grand_pa_agent_bonus_result = $member
                ->where('uid', $grand_pa->uid)
                ->setInc('balance', $quota);
            // 记录父级的父级代理商收入记录
            $distribution_grand_pa_agent_bonus_income = $income
                ->isUpdate(false)
                ->data([
                    'uid' => $grand_pa->uid,
                    'type' => 2,
                    'quota' => $quota,
                    'description' => '二级盟友['.$order_info->nickname.']',
                    'from_uid' => $order_info->uid
                ])
                ->save();
        }
        if (
            $distribution_parent_member_result &&
            $distribution_parent_member_bonus_result &&
            $distribution_parent_agent_result &&
            $distribution_parent_agent_bonus_result &&
            $distribution_grand_pa_member_result &&
            $distribution_grand_pa_member_bonus_result &&
            $distribution_grand_pa_agent_result &&
            $distribution_grand_pa_agent_bonus_result &&
            $distribution_parent_member_income &&
            $distribution_parent_agent_bonus_income &&
            $distribution_grand_pa_agent_bonus_income &&
            $distribution_grand_pa_member_bonus_income
        ) {
            $member->commit();
            return true;
        }
        return false;
    }
}